package com.slwish.xty.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.slwish.common.base.BaseActivity;
import com.slwish.common.config.Contants;
import com.slwish.common.utils.KeyBoardUtils;
import com.slwish.common.utils.SpUtils;
import com.slwish.common.utils.StringUtils;
import com.slwish.xty.R;
import com.slwish.xty.interf.OnFragmentInteractionListener;
import com.slwish.xty.ui.fragment.SearchListFragment;
import com.slwish.xty.ui.fragment.SearchListHistoryFragment;
import com.slwish.xty.widget.ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索
 */
public class SearchListActivity extends BaseActivity implements OnFragmentInteractionListener {
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.et_username)
    ClearEditText etSearch;
    FragmentManager fm;
    //首先需要先实例好n个全局Fragment
    private Fragment currentFragment;//（全局）
//    private FragmentTransaction fragmentTransaction;
    SearchListHistoryFragment searchListHistoryFragment;
    SearchListFragment searchListFragment;
    private long usetId;

    @Override
    protected int getLayoutId() {
        return R.layout.act_search_list;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        usetId = SpUtils.getLong(mContext, Contants.UserCode, 0);
        searchListHistoryFragment = SearchListHistoryFragment.newInstance("", "");
        switchFragment("");
    }

    public long getUsetId() {
        return usetId;
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchMessage = etSearch.getText().toString();
                    if (fm.getBackStackEntryCount() <= 1) {
                        //隐藏键盘
                        switchFragment(searchMessage);//切换fragment
                    } else {
                        searchListFragment.notifyList(searchMessage);
                    }
                    if (!StringUtils.isEmpty(searchMessage)) {
                        String historyLabel = (String) SpUtils.get(mContext, Contants.HISTORY_LABEL, "");
                        if (historyLabel.contains(searchMessage))
                            historyLabel =  historyLabel.replace(","+searchMessage+",",",");
                            SpUtils.put(mContext, Contants.HISTORY_LABEL, "," + searchMessage + historyLabel);
//                        HistorySearchModel model = new HistorySearchModel(usetId, searchMessage);
//                        model.saveOrUpdate("label = ?", searchMessage);
                        searchListHistoryFragment.refreshHistory();
                    }
                    KeyBoardUtils.hideKeyBoard(mContext, v);
                    return true;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.tv_cancel, R.id.iv_left})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
                backStack();

                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    /**
     * 回退栈
     */
    private void backStack() {
        int entryCount = fm.getBackStackEntryCount();
        if (entryCount > 1) {
            fm.popBackStack();
            currentFragment = searchListHistoryFragment;
            ivLeft.setVisibility(View.GONE);
//            switchFragment(etSearch.getText().toString());
        } else {
            finish();
        }
    }

    @Override
    public void onFragmentInteraction(String message) {
        etSearch.setText(message);
        switchFragment(message);

    }

    private void switchFragment(String message) {
        Fragment fragment;
        fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (currentFragment == searchListHistoryFragment) {
            //第一次使用switchFragment()时currentFragment为null，所以要判断一下
//            transaction.hide(currentFragment);
            if (searchListFragment == null) {
                searchListFragment = SearchListFragment.newInstance("", "");
            }
            fragment = searchListFragment;
            ivLeft.setVisibility(View.VISIBLE);
            Bundle bundle = new Bundle();
            bundle.putString(SearchListFragment.ARG_PARAM1, message);
            searchListFragment.setArguments(bundle);
        } else {
            fragment = searchListHistoryFragment;
            ivLeft.setVisibility(View.GONE);
        }
        currentFragment = fragment;
        transaction.replace(R.id.fragment_content, fragment, fragment.getClass().getName());
        transaction.addToBackStack(fragment.getClass().getName());
        transaction.commit();
    }

    @Override
    public void onBackPressed() {
        backStack();
//        if (fm.getBackStackEntryCount() > 1) {
//            fm.popBackStack();
//        } else {
//            super.onBackPressed();
//        }
    }
}
